using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

namespace viBook.Models
{
    public class BookRepository : IBookRepository
    {
        private readonly viBookContext _context;
        private readonly IChapterRepository _chapterRepository;
        private readonly IAuthorRepository _authorRepository;
        public BookRepository()
            : this(new AuthorRepository(), new ChapterRepository())
        {

        }

        public BookRepository(IAuthorRepository authorRepositoryRepository, IChapterRepository chapterRepository)
        {
            _context = new viBookContext();
            _authorRepository = authorRepositoryRepository;
            _chapterRepository = chapterRepository;
        }

        public IQueryable<Book> All
        {
            get { return _context.Books; }
        }

        public IQueryable<Book> AllIncluding(params Expression<Func<Book, object>>[] includeProperties)
        {
            IQueryable<Book> query = _context.Books;
            foreach (var includeProperty in includeProperties)
            {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public Book Find(int id)
        {
            var book = _context.Books.Find(id);
            book.AuthorName = _authorRepository.Find(book.AuthorId).AuthorName;
            book.Chapters = new List<Chapter>();
            _chapterRepository.GetAllChaptersByBookId(id);
            return book;
        }

        public IQueryable<Book> FindAllBookByUserId(int userId)
        {
            return _context.Books.
                Where(b => b.UploadedBy == userId);
        }


        public void InsertOrUpdate(Book book)
        {
            book.AuthorId = _authorRepository.FindAuthorsiId(book.AuthorName);
            if (book.Id == default(int))
            {
                _context.Books.Add(book);
            }
            else
            {
                _context.Entry(book).State = EntityState.Modified;
            }
        }

        public void Delete(int id)
        {
            _chapterRepository.DeleteChaptersInBook(id);
            var book = _context.Books.Find(id);
            _context.Books.Remove(book);
        }

        public void Save()
        {
            _context.SaveChanges();
        }
    }

    public interface IBookRepository
    {
        IQueryable<Book> All { get; }
        IQueryable<Book> AllIncluding(params Expression<Func<Book, object>>[] includeProperties);
        Book Find(int id);
        IQueryable<Book> FindAllBookByUserId(int userId);
        void InsertOrUpdate(Book book);
        void Delete(int id);
        void Save();
    }
}
